<?php

namespace app\controllers;

use app\lib\BaseFunction;
use app\models\Bank_bill;
use app\models\ContainerModel;
use app\models\ContainerProductModel;
use app\models\CouponModal;
use app\models\Customer;
use app\models\Income;
use app\models\Invoice;
use app\models\Invoice_new;
use app\models\Pi;
use app\models\Purchase;
use app\models\Quote;
use app\models\QuoteProduct;
use app\models\SampleOrder;
use app\models\Staff;
use app\service\ContainerProductService;
use app\service\SellService;
use app\service\StaffService;
use yii;
use yii\helpers\Url;

//销售管理模块

/**
 * 流程 报价->pi->invoice
 */
class SellController extends CommonController
{
    public $layout = false;

    public function actionIndex()
    {
        //收款排行榜
        $model = new Income();
        $list1 = $model->sumIncomebyMonth(date('Y-m'));
        $list1 = array_reverse($this->mysort($list1, 'income'));
        //订单排行榜
        $model = new Invoice_new();
        $list2 = $model->getInvoiceNum(date('Y-m'));
        $list2 = array_reverse($this->mysort($list2, 'num'));
        $model = new Staff();
        $staff = $model->get_all_saleman();
        return $this->render('index', ['list1' => $list1, 'list2' => $list2, 'staff' => $staff]);
    }

    //这是报价
    public function actionQuote_list()
    {
        $p                      = yii::$app->request->get('p') ? yii::$app->request->get('p') : 1;
        $s                      = yii::$app->request->get('s') ? yii::$app->request->get('s') : 15;
        $where                  = [];
        $where['quote_id']      = yii::$app->request->get('quote_id');
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['product']       = yii::$app->request->get('product');
        $pi_model               = new \app\models\Pi();
        $pi_list                = $pi_model->get_pi_list_by_quote();
        $arr                    = [];
        foreach ($pi_list as $k => $v) {
            $arr[] = $v['quote_id'];
        }
        yii::$app->view->params['pi_list'] = $arr;

        $model = new Quote();
        if ($this->user['role'] == 1 || $this->user['role'] == 2) {
        } else {
            $where['job_number'] = $this->user['job_number'];
        }
        $list    = $model->get_quote_list($p, $s, $where);
        $size    = $model->get_quote_size($where);
        $oldlist = $model->get_all_older_quote_list($where);
        $oldarr  = [];
        foreach ($oldlist as $k => $v) {
            $oldarr[$v['quote_id']][] = $v;
        }
        $page                                 = ceil($size / $s);
        yii::$app->view->params['total_size'] = $size;
        $base_url                             = '/sell/quote_list' . $this->get_base_url();
        yii::$app->view->params['page']       = ['curr' => $p, 'page' => $page, 'url' => $base_url];
        yii::$app->view->params['oldlist']    = $oldarr;
        yii::$app->view->params['list']       = $list;
        return $this->render('quote_list');
    }

    /**报价api
     * @return string
     */
    public function actionQuote()
    {
        $p                      = yii::$app->request->get('p') ? yii::$app->request->get('p') : 1;
        $s                      = yii::$app->request->get('s') ? yii::$app->request->get('s') : 15;
        $where                  = [];
        $where['number']        = yii::$app->request->get('number', '');
        $where['quote_id']      = yii::$app->request->get('quote_id', '');
        $where['customer_name'] = trim(yii::$app->request->get('buyer'));
        $where['product']       = yii::$app->request->get('product');

        $model = new Quote();
        if ($this->user['role'] == 1 || $this->user['role'] == 2) {
        } else {
            $where['job_number'] = $this->user['job_number'];
        }
        $list = $model->get_quote_list($p, $s, $where);
        $size = $model->get_quote_size($where);
        foreach ($list as $k => $v) {
            $list[$k]['customer_info'] = json_decode($v['customer_info']);
            $list[$k]['product_list']  = json_decode($v['product_list']);
        }
        $quoteArr = array_column($list, 'id');

        //获取历史记录
        $oldlist = $model->get_all_older_quote_list($where);
        $oldarr  = [];
        foreach ($oldlist as $k => $v) {
            $oldarr[$v['quote_id']][] = $v;
        }
        //PI信息
        if ($quoteArr) {
            $piModel = new \app\models\Pi();
            $piList  = $piModel->get_pi_list_by_quote(['quote_id' => $quoteArr]);
        } else {
            $piList = [];
        }

        return json_encode(['pi' => $piList, 'list' => $list, 'old_list' => $oldlist, 'total' => (int) $size]);
    }

    public function actionGetquote()
    {
        $user                            = $this->user;
        yii::$app->view->params['param'] = ['email' => $user['email'], 'sale_rep' => $user['en_name']];
        return $this->render('quote');
    }

    /**
     * 添加报价操作
     */
    public function actionAdd_quote()
    {
        $data['date']              = yii::$app->request->post('date', date('Y-m-d'));
        $data['sale_rep']          = yii::$app->request->post('sale_rep', '');
        $data['email']             = yii::$app->request->post('email', '');
        $data['list']              = yii::$app->request->post('list');
        $data['customer_info']     = yii::$app->request->post('customer_info');
        $data['number']            = yii::$app->request->post('number');
        $data['para']              = json_encode(yii::$app->request->post('para')); //段落
        $data['duty']              = json_encode(yii::$app->request->post('duty')); //税费
        $data['ship']              = json_encode(yii::$app->request->post('ship')); //运费
        $data['service']           = yii::$app->request->post('service');
        $data['total_amount_show'] = yii::$app->request->post('total_amount_show');
        $data['subtotal_show']     = yii::$app->request->post('subtotal_show');
        $data['extra_fee_show']    = yii::$app->request->post('extra_fee_show');
        $data['service']           = json_encode($data['service']);
        //生成一个报价编号
        $model            = new \app\models\Quote();
        $re               = $model->get_quote_id();
        $quote_num        = $re ? ($re['num'] + 1) : 1;
        $data['quote_id'] = 'Q' . date('ymd') . str_pad($quote_num, 3, 0, STR_PAD_LEFT);

        $list              = json_decode($data['list'], true);
        $arr               = [];
        $quoteProductModel = new QuoteProduct();
        foreach ($list as $k => $v) {
            if ($v['item']) {
                $tmp                 = $v;
                $tmp['product_name'] = $v['item'];
                $tmp['job_number']   = $this->user['job_number'];
                $tmp['date']         = date('Y-m-d');
                $tmp['img_src']      = !empty($v['img_src']) ? $v['img_src'][0] : '';
                unset($tmp['item']);
                unset($tmp['extra_fee']);
                unset($tmp['subtotal']);
                $quoteProductModel->insert($tmp);
                $arr[] = $v;
            }
        }

        //数据录入数据库`
        $user        = $this->user;
        $insert_data = [
            'date'              => $data['date'],
            'job_number'        => $user['job_number'],
            'sale_rep'          => $data['sale_rep'],
            'customer_info'     => json_encode($data['customer_info']),
            'product_list'      => json_encode($arr),
            'number'            => $data['number'],
            'quote_id'          => $data['quote_id'],
            'para'              => $data['para'],
            'ship'              => $data['ship'],
            'duty'              => $data['duty'],
            'service'           => $data['service'],
            'extra_fee_show'    => $data['extra_fee_show'],
            'total_amount_show' => $data['total_amount_show'],
            'subtotal_show'     => $data['subtotal_show'],
            'create_at'         => time(),
        ];
        $model = new Quote();
        $re    = $model->add_quote($insert_data);
        $id    = Yii::$app->db->getLastInsertID();
        if (!$re) {
            echo json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
        } else {
            echo json_encode(['code' => 1, 'msg' => '添加成功', 'id' => $id]);
        }
    }

    public function actionQuote_edit()
    {
        $id = yii::$app->request->get('id');
        if (is_numeric($id)) {
            $model                          = new \app\models\Quote();
            $info                           = $model->get_quote_by_id($id);
            yii::$app->view->params['info'] = $info;
            return $this->render('quote_edit');
        } else {
            return $this->render('/public/404');
        }
    }

    public function actionQuote_edit_act()
    {

        $id = yii::$app->request->post('id');
        //复制一条记录
        $model                     = new \app\models\Quote();
        $data                      = $model->get_quote_info_by_id($id);
        $data['date']              = yii::$app->request->post('date');
        $data['customer_info']     = json_encode(yii::$app->request->post('customer_info'));
        $data['product_list']      = yii::$app->request->post('list');
        $data['para']              = json_encode(yii::$app->request->post('para')); //段落
        $data['duty']              = json_encode(yii::$app->request->post('duty')); //税费
        $data['ship']              = json_encode(yii::$app->request->post('ship')); //运费
        $data['service']           = yii::$app->request->post('service');
        $data['service']           = json_encode($data['service']);
        $data['create_at']         = time();
        $data['extra_fee_show']    = yii::$app->request->post('extra_fee_show');
        $data['subtotal_show']     = yii::$app->request->post('subtotal_show');
        $data['total_amount_show'] = yii::$app->request->post('total_amount_show');
        $list                      = json_decode($data['product_list'], true);
        $arr                       = [];
        foreach ($list as $k => $v) {
            if ($v['item']) {
                $arr[] = $v;
            }
        }
        $data['product_list'] = json_encode($arr);
        //获取当前quote最大版本;
        $version         = $model->get_max_version_by_quote_num($data['quote_id']);
        $data['version'] = $version['version'] + 1;
        unset($data['id']);
        $re = yii::$app->db
            ->createCommand()
            ->insert(yii::$app->db->tablePrefix . "quote", $data)
            ->execute();

        if ($re) {
            $id = Yii::$app->db->getLastInsertID();
            echo json_encode(['code' => 1, 'msg' => '编辑成功', 'id' => $id]);
        } else {
            echo json_encode(['code' => 0, 'msg' => '编辑失败，请重试']);
        }
    }

    /**
     * paypal订单列表
     */
    public function actionPaypalOrder()
    {
        $page     = yii::$app->request->get('page', 1);
        $pageSize = yii::$app->request->get('per-page', 10);
        $where    = [];
        if ($this->user['role'] != 1) {
            $where['staff'] = $this->user['job_number'];
        }
        $model = new SampleOrder();
        $list  = $model->all($where, ($page - 1) * $pageSize, $pageSize, ['create_at' => SORT_DESC]);
        $size  = $model->size($where);
        $model = new Staff();
        $staff = $model->get_all_saleman();
        //客户信息添加
        $customerArr  = array_column($list, 'user_id');
        $model        = new Customer();
        $customerList = $model->getCustomerById($customerArr);
        foreach ($list as $k => $v) {
            $list[$k]['customer_name'] = '';
            $list[$k]['customer_num']  = '';
            foreach ($customerList as $v2) {
                if ($v['user_id'] == $v2['id']) {
                    $list[$k]['customer_name'] = $v2['customer_name'];
                    $list[$k]['customer_num']  = $v2['number'];
                }
            }
        }
        $pagenation = new \yii\data\Pagination(['totalCount' => $size, 'pagesize' => $pageSize]);
        return $this->render('paypalorder', ['staff' => $staff, 'list' => $list, 'page' => $pagenation]);
    }

    //pi
    public function actionPi()
    {
        if (yii::$app->request->isGet) {
            //获取一个pi编号
            $model = new \app\models\Pi();
            $pi_id = $model->get_pi_number();

            $quote_id = (int) yii::$app->request->get('id');
            //基于当前报价生成pi
            $quote_model                     = new \app\models\Quote();
            $quote_info                      = $quote_model->get_quote_by_id($quote_id);
            yii::$app->view->params['quote'] = $quote_info;
            $user                            = $this->user;
            yii::$app->view->params['param'] = ['pi_id' => $pi_id, 'email' => $user['email'], 'sale_rep' => $user['en_name']];
            return $this->render('pi');
        }
    }

    public function actionAdd_pi()
    {

        $data['date']              = yii::$app->request->post('date');
        $data['sale_rep']          = yii::$app->request->post('sale_rep');
        $data['email']             = yii::$app->request->post('email');
        $data['list']              = yii::$app->request->post('list');
        $data['customer_info']     = yii::$app->request->post('customer_info');
        $data['number']            = yii::$app->request->post('number');
        $data['para']              = json_encode(yii::$app->request->post('para')); //段落
        $data['duty']              = json_encode(yii::$app->request->post('duty')); //税费
        $data['ship']              = json_encode(yii::$app->request->post('ship')); //运费
        $data['service']           = yii::$app->request->post('service');
        $data['total_amount_show'] = yii::$app->request->post('total_amount_show');
        $data['subtotal_show']     = yii::$app->request->post('subtotal_show');
        $data['extra_fee_show']    = yii::$app->request->post('extra_fee_show');
        $data['service']           = json_encode($data['service']);
        $data['pi_id']             = yii::$app->request->post('pi_id');
        $data['quote_id']          = yii::$app->request->post('quote_id');
        $data['pay_show']          = yii::$app->request->post('pay_show');
        $list                      = json_decode($data['list'], true);
        $arr                       = [];
        foreach ($list as $k => $v) {
            if ($v['item']) {
                $arr[] = $v;
            }
        }

        $model = new Pi();
        $pi_id = $model->get_pi_number();

        //数据录入数据库
        $user        = $this->user;
        $insert_data = [
            'date'              => $data['date'],
            'job_number'        => $user['job_number'],
            'sale_rep'          => $data['sale_rep'],
            'customer_info'     => json_encode($data['customer_info']),
            'product_list'      => json_encode($arr),
            'number'            => $data['number'],
            'pi_id'             => $pi_id,
            'para'              => $data['para'],
            'ship'              => $data['ship'],
            'duty'              => $data['duty'],
            'service'           => $data['service'],
            'extra_fee_show'    => $data['extra_fee_show'],
            'total_amount_show' => $data['total_amount_show'],
            'subtotal_show'     => $data['subtotal_show'],
            'create_at'         => time(),
            'quote_id'          => $data['quote_id'],
            'pay_show'          => $data['pay_show'],
        ];

        $re = $model->add_pi($insert_data);
        if (!$re) {
            echo json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
            return false;
        } else {
            echo json_encode(['code' => 1, 'msg' => '添加成功']);
        }
    }

    public function actionPi_list()
    {

        $model      = new Staff();
        $staff_list = $model->get_all_saleman();
        foreach ($staff_list as $v) {
            $satff_list[$v['job_number']] = $v['name'];
        }
        $p                   = yii::$app->request->get('p') ? yii::$app->request->get('p') : 1;
        $s                   = yii::$app->request->get('s') ? yii::$app->request->get('s') : 15;
        $where['job_number'] = yii::$app->request->get('staff');
        $where['pi_id']      = yii::$app->request->get('pi');
        $model               = new Pi();
        //超级管理员查看全部
        //财务查看全部
        if ($this->user['role'] == 1 || $this->user['role'] == 2) {

        } else {
            $where['job_number'] = $this->user['job_number'];
        }
        $list         = $model->get_pi_by_job_number($p, $s, $where);
        $old_list     = $model->get_all_older_pi($where);
        $size         = $model->get_pi_size_by_job_number($where);
        $old_list_arr = [];
        foreach ($old_list as $v) {
            $old_list_arr[$v['pi_id']][] = $v;
        }

        unset($old_list);
        yii::$app->view->params['oldlist'] = $old_list_arr;
        foreach ($list as $k => $v) {
            $list[$k]['name'] = $satff_list[$v['job_number']];
        };
        $page = $size ? ceil($size / $s) : 1;

        $model                                = new Invoice();
        $pi_arr                               = $model->get_all_pi_id();
        yii::$app->view->params['staff_list'] = $staff_list;
        yii::$app->view->params['pi_arr']     = $pi_arr;
        $base_url                             = '/sell/pi_list' . $this->get_base_url();
        yii::$app->view->params['page']       = ['page' => $page, 'curr' => $p, 'url' => $base_url];
        yii::$app->view->params['list']       = $list;
        return $this->render('pi_list');
    }

    public function actionPi_edit()
    {
        if (is_numeric($id = yii::$app->request->get('id'))) {
            $model                          = new Pi();
            $info                           = $model->get_pi_by_id($id);
            $user                           = $this->user;
            $info['email']                  = $user['email'];
            yii::$app->view->params['info'] = $info;
            return $this->render('pi_edit');
        }
    }

    public function actionPi_edit_act()
    {
        $id = yii::$app->request->post('id');
        //复制一条记录
        $model = new \app\models\Pi();
        $data  = $model->get_pi_by_id($id);
        unset($data['id']);
        $data['date']              = yii::$app->request->post('date');
        $data['customer_info']     = json_encode(yii::$app->request->post('customer_info'));
        $data['product_list']      = yii::$app->request->post('list');
        $data['para']              = json_encode(yii::$app->request->post('para')); //段落
        $data['duty']              = json_encode(yii::$app->request->post('duty')); //税费
        $data['ship']              = json_encode(yii::$app->request->post('ship')); //运费
        $data['service']           = yii::$app->request->post('service');
        $data['service']           = json_encode($data['service']);
        $data['create_at']         = time();
        $data['extra_fee_show']    = yii::$app->request->post('extra_fee_show');
        $data['subtotal_show']     = yii::$app->request->post('subtotal_show');
        $data['total_amount_show'] = yii::$app->request->post('total_amount_show');
        $data['pay_show']          = yii::$app->request->post('pay_show');
        $list                      = json_decode($data['product_list'], true);
        $arr                       = [];
        foreach ($list as $k => $v) {
            if ($v['item']) {
                $arr[] = $v;
            }
        }
        $data['product_list'] = json_encode($arr);
        //当前pi版本
        $model           = new \app\models\Pi();
        $info            = $model->get_max_pi_version($data['pi_id']);
        $data['version'] = $info['num'] + 1;
        $re              = $model->add_pi($data);
        if ($re) {
            $id = yii::$app->db->getLastInsertId();
            echo json_encode(['code' => 1, 'msg' => "更新成功", 'id' => $id]);
        } else {
            echo json_encode(['code' => 0, 'msg' => '更新失败,请重试']);
        }
    }

    //最终订单
    public function actionInvoice()
    {
        $id = yii::$app->request->get('id');
        if (intval($id) > 0) {

            //通过报价生成invocie其他信息
            $piModel      = new Pi();
            $pi_info      = $piModel->get_pi_by_id($id);
            $product_list = json_decode($pi_info['product_list'], true);
            foreach ($product_list as $k => $v) {
                if (!isset($v['type'])) {
                    $product_list[$k]['type'] = '';
                }
            }
            $pi_info['product_list']           = json_encode($product_list);
            yii::$app->view->params['pi_info'] = $pi_info;
            $user                              = $this->user;
            yii::$app->view->params['param']   = ['email' => $user['email'], 'sale_rep' => $user['en_name']];
            return $this->render('invoice');
        } else {
            $user                            = $this->user;
            yii::$app->view->params['param'] = ['job_number' => $user['job_number'], 'email' => $user['email'], 'sale_rep' => $user['en_name']];
            return $this->render('invoice_empty_add');
        }
    }

    /**invoice列表
     * @return string
     */
    public function actionInvoice_list()
    {
        $where                  = [];
        $p                      = yii::$app->request->get('p') ? yii::$app->request->get('p') : 1;
        $s                      = yii::$app->request->get('s') ? yii::$app->request->get('s') : 15;
        $where['invoice']       = trim(yii::$app->request->get('invoice'));
        $where['job_number']    = yii::$app->request->get('job_number');
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['show_invoice']  = yii::$app->request->get('show_invoice');
        $model                  = new Invoice();
        if (!($this->user['role'] == 1 || $this->user['role'] == 2)) {
            $where['job_number']                = $this->user['job_number'];
            yii::$app->view->params['show_del'] = false;
        } else {
            yii::$app->view->params['show_del'] = true;
        }

        $list = $model->get_invoice_list_by_job_number($p, $s, $where);

        $size = $model->get_invoice_size_by_job_number($where);

        $tmp = [];
        foreach ($list as $v) {
            $tmp[] = $v['pi_id'];
        }
        $piModel = new Pi();
        $piList  = $piModel->getPi($tmp);
        foreach ($list as $k => $v) {
            if ($v['pi_id'] == 111) {
                $list[$k]['pi_id'] = '';
                continue;
            }
            foreach ($piList as $v2) {
                if ($v['pi_id'] == $v2['id']) {
                    $list[$k]['pi_id'] = $v2['pi_id'];
                }
            }
        }
        $page        = $size ? ceil($size / $s) : 1;
        $staff_model = new Staff();
        $staffList   = $staff_model->get_all_saleman();
        $old_arr     = [];
        foreach ($list as $k => $v) {
            $old_arr[] = $v['id'];
        }
        //历史版本
        yii::$app->view->params['staffList'] = $staffList;
        $oldlist                             = $model->get_older_version($old_arr);
        yii::$app->view->params['oldlist']   = $oldlist;
        $base_url                            = '/sell/invoice_list' . $this->get_base_url();
        yii::$app->view->params['page']      = ['page' => $page, 'curr' => $p, 'url' => $base_url];
        yii::$app->view->params['list']      = $list;
        return $this->render('invoice_list');
    }

    public function actionInvoice_edit()
    {
        if (is_numeric($id = yii::$app->request->get('id'))) {
            $model       = new Invoice();
            $info        = $model->get_invoice_by_id($id);
            $productList = json_decode($info['product_list'], true);
            foreach ($productList as $k2 => $v2) {
                if (!isset($v2['type'])) {
                    $productList[$k2]['type'] = "";
                }
            }
            $model                = new CouponModal();
            $res                  = $model->one('*', ['number_no' => $info['coupon_num']]);
            $info['free']         = $res['detail']['free'];
            $info['product_list'] = json_encode($productList);
            return $this->render('invoice_edit', ['info' => $info]);
        }
    }

    public function actionDelInvoice()
    {
        if (yii::$app->request->isPost) {
            BaseFunction::check_edit_auth($this->user['role']);
            $id    = yii::$app->request->post('id');
            $model = new Invoice();
            $re    = $model->delInvoice($id);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '删除成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '删除失败，请重试']);
            }
        }

    }

    public function actionInvoice_edit_act()
    {
        $id = yii::$app->request->post('id');
        if (!is_numeric($id)) {
            return json_encode(['code' => 0, 'msg' => '非法数据']);
        }
        $model       = new Invoice();
        $data        = $model->clone_invoice_by_id($id);
        $data['pid'] = $data['id'];
        unset($data['id']);
        yii::$app->db->createCommand()->insert(yii::$app->db->tablePrefix . 'invoice', $data)->execute();
        unset($data['pid']);
        $data['date']              = yii::$app->request->post('date');
        $data['customer_info']     = json_encode(yii::$app->request->post('customer_info'));
        $data['product_list']      = yii::$app->request->post('list');
        $data['para']              = json_encode(yii::$app->request->post('para')); //段落
        $data['duty']              = json_encode(yii::$app->request->post('duty')); //税费
        $data['ship']              = json_encode(yii::$app->request->post('ship')); //运费
        $data['service']           = yii::$app->request->post('service');
        $data['service']           = json_encode($data['service']);
        $data['create_at']         = time();
        $data['extra_fee_show']    = yii::$app->request->post('extra_fee_show');
        $data['subtotal_show']     = yii::$app->request->post('subtotal_show');
        $data['total_amount_show'] = yii::$app->request->post('total_amount_show');
        $data['pay_show']          = yii::$app->request->post('pay_show');
        $couponNum                 = yii::$app->request->post('coupon_id');
        //优惠券信息
        $haveCoupon = yii::$app->request->post('coupon') === 'true' ? true : false;
        if (!$haveCoupon) {
            //将原先优惠券设置成未使用
            yii::$app->db->createCommand()
                ->update('jingsourcing_coupon', ['is_active' => 1], ['number_no' => $data['coupon_num']])
                ->execute();
            $data['coupon_num'] = '';
        }
        if ($haveCoupon && $couponNum != $data['coupon_num']) {
            $data['coupon_num'] = $couponNum;
            yii::$app->db->createCommand()
                ->update('jingsourcing_coupon', ['is_active' => 2], ['number_no' => $couponNum])
                ->execute();
        }

        unset($data['id']);
        $list = json_decode($data['product_list'], true);
        $arr  = [];
        foreach ($list as $k => $v) {
            if ($v['item']) {
                $arr[] = $v;
            }
        }
        $data['product_list'] = json_encode($arr);
        $data['create_at']    = time();
        $data['version']++;
        //标记优惠券信息
        $re = yii::$app->db->createCommand()->update(yii::$app->db->tablePrefix . 'invoice', $data, ['id' => $id])->execute();

        if ($re) {
            echo json_encode(['code' => 1, 'msg' => '更新成功', 'id' => $id]);
        } else {
            echo json_encode(['code' => 0, 'msg' => '更新失败,请重试']);
        }

    }

    public function actionInvoiceEditByParam()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id');
            $param = yii::$app->request->post('param');
            $value = trim(yii::$app->request->post('value'));
            $model = new Invoice();
            $re    = $model->updateInvoice([$param => $value], $id);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '修改成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '修改失败,请重试']);
            }
        }
    }

    public function actionAdd_invoice()
    {
        $data['date']              = yii::$app->request->post('date');
        $data['sale_rep']          = yii::$app->request->post('sale_rep');
        $data['email']             = yii::$app->request->post('email');
        $data['list']              = yii::$app->request->post('list');
        $data['customer_info']     = yii::$app->request->post('customer_info');
        $data['number']            = yii::$app->request->post('number');
        $data['para']              = json_encode(yii::$app->request->post('para')); //段落
        $data['duty']              = json_encode(yii::$app->request->post('duty')); //税费
        $data['ship']              = json_encode(yii::$app->request->post('ship')); //运费
        $data['service']           = yii::$app->request->post('service');
        $data['total_amount_show'] = yii::$app->request->post('total_amount_show');
        $data['subtotal_show']     = yii::$app->request->post('subtotal_show');
        $data['extra_fee_show']    = yii::$app->request->post('extra_fee_show');
        $data['service']           = json_encode($data['service']);
        $data['pi_id']             = yii::$app->request->post('pi_id', '');
        $data['pay_show']          = yii::$app->request->post('pay_show');
        $data['job_number']        = yii::$app->request->post('job_number');
        //清除产品无效列
        $list = json_decode($data['list'], true);
        $arr  = [];
        foreach ($list as $k => $v) {
            if ($v['item']) {
                $arr[] = $v;
            }
        }
        $data['coupon_num'] = yii::$app->request->post('coupon_id', '');
        if ($data['coupon_num']) {
            yii::$app->db->createCommand()
                ->update('jingsourcing_coupon', ['is_active' => 2], ['number_no' => $data['coupon_num']])
                ->execute();
        }
        $insert_data = [
            'date'              => $data['date'],
            'job_number'        => $data['job_number'],
            'sale_rep'          => $data['sale_rep'],
            'customer_info'     => json_encode($data['customer_info']),
            'product_list'      => json_encode($arr),
            'number'            => $data['number'],
            'para'              => $data['para'],
            'ship'              => $data['ship'],
            'duty'              => $data['duty'],
            'service'           => $data['service'],
            'extra_fee_show'    => $data['extra_fee_show'],
            'total_amount_show' => $data['total_amount_show'],
            'subtotal_show'     => $data['subtotal_show'],
            'create_at'         => time(),
            'pi_id'             => $data['pi_id'],
            'pay_show'          => $data['pay_show'],
            'coupon_num'        => $data['coupon_num'],
        ];
        $model = new Invoice();
        $re    = $model->add_invoice($insert_data);
        if ($re) {
            echo json_encode(['code' => 1, 'msg' => '添加成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
        }
    }

    /**
     *采购合同界面
     *
     */
    public function actionPurchase()
    {
        //生成一个采购编号
        $model = new \app\models\Purchase();
        do {
            $num = 'CG' . date('ymd') . rand(1000, 10000);
            $re  = $model->check_purchase_num($num);
        } while ($re);
        $p                                  = yii::$app->request->get("p") ? yii::$app->request->get("p") : 1;
        $s                                  = yii::$app->request->get("s") ? yii::$app->request->get("s") : 10;
        $model                              = new \app\models\Invoice();
        $list                               = $model->get_invoice_list_by_job_number($p, $s, $this->user['job_number']);
        yii::$app->view->params['list']     = $list;
        yii::$app->view->params['purchase'] = $num;
        yii::$app->view->params['zh_name']  = $this->user['zh_name'];
        return $this->render('purchase');
    }

    /**采购合同列表
     * @return string
     */
    public function actionPurchase_list()
    {
        $p = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
//        echo json_encode($this->user);exit;
        $where                          = [];
        $where['invoice']               = trim(yii::$app->request->get('invoice'));
        $where['purchase_num']          = trim(yii::$app->request->get('purchase_num'));
        $where['job_number']            = trim(yii::$app->request->get('job_number'));
        $where['product_status']        = yii::$app->request->get('product_status');
        $where['product_status_time']   = yii::$app->request->get('product_status_time');
        $where['pay_status']            = yii::$app->request->get('pay_status');
        $where['last_modify']           = yii::$app->request->get('last_modify');
        yii::$app->view->params['show'] = true;
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            if (BaseFunction::checkJieke($this->user['role'])) {
                if ($this->user['role'] == 9) {
                    $where['job_number'] = $this->user['job_number'];
                } else {
                    if (empty($where['job_number'])) {
                        $model               = new Staff();
                        $job_number          = $model->getStaffByGroup(4);
                        $where['job_number'] = $job_number;
                    }
                }
            } else {
                $where['job_number'] = $this->user['job_number'];
            }
            yii::$app->view->params['show'] = false;
        }

        $sellService                    = new SellService();
        $data                           = $sellService->purchaseList($p, $s, $where);
        $list                           = $data['list'];
        $size                           = $data['size'];
        $page                           = $size ? ceil($size / $s) : 1;
        $baseUrl                        = '/sell/purchase_list' . $this->get_base_url();
        yii::$app->view->params['page'] = [
            'page'    => $page,
            'current' => $p,
            'baseUrl' => $baseUrl,
        ];
        yii::$app->view->params['purchase'] = $data['purchase'];
        yii::$app->view->params['staff']    = $data['staff'];
        yii::$app->view->params['list']     = $list;

        return $this->render('purchase_list', ['purchase' => $data['purchase'], 'staff' => $data['staff'], 'list' => $list, 'role' => $this->user['role']]);
    }

    /**
     * 更新采购合同参数
     * 改
     */
    public function actionUpdatePurchaseAct()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id');
            $param = yii::$app->request->post('param');
            $value = yii::$app->request->post('value');
            if ($param == 'product_status') {
                $data['product_status_time'] = date('Y-m-d');
            }
            $data[$param] = $value;
            if (is_numeric($id)) {
                try {
                    $re = yii::$app->db->createCommand()
                        ->update(yii::$app->db->tablePrefix . 'purchase', $data, ['id' => $id])
                        ->execute();
                } catch (\Exception $e) {
                    $msg = $e->getMessage();
                    return json_encode(['code' => 0, 'msg' => $msg]);
                }

                if ($re) {
                    //更新排柜信息
                    //获取当前采购编号
                    $model = new Purchase();
                    $info  = $model->one(['id' => $id]);
                    if ($info && $param == 'product_status') {
                        $model = new ContainerProductModel();
                        if ($info['product_status'] == 2) {
                            $update = ['status' => 2];
                        } else if ($info['product_status'] == 3) {
                            $update = ['status' => 3];
                        }
                        $model->save($update, ['purchase_num' => $info['purchase_num']]);
                    }

                    echo json_encode(['code' => 1, 'msg' => '更新成功']);
                } else {
                    echo json_encode(['code' => 0, 'msg' => '更新失败，请重试']);
                }
            }
        }
    }

    /**
     * 采购合同编辑
     *
     */
    public function actionPurchase_edit()
    {
        if (yii::$app->request->isGet) {
            $id                                = yii::$app->request->get('id');
            $model                             = new \app\models\Purchase();
            $info                              = $model->get_purchase_by_id($id);
            yii::$app->view->params['info']    = $info;
            yii::$app->view->params['zh_name'] = $this->user['zh_name'];

            return $this->render('purchase_edit');
        } elseif (yii::$app->request->isPost) {
            $id   = yii::$app->request->post('id');
            $data = yii::$app->request->post('data');
            $data = json_decode($data, true);
            unset($data['zh_name']);
            $data['total_fee'] = 0;
            if ($data['ship_fee_show']) {
                $data['total_fee'] += $data['ship_fee'];
            }
            foreach ($data['product_list'] as $k => $v) {
                if (!$v['item']) {
                    unset($data['product_list'][$k]);
                } else {
                    $data['total_fee'] += $v['total'];
                }
            }
            $data['product_list'] = json_encode($data['product_list']);
            $model                = new Purchase();
            $re                   = $model->save($data, ['id' => $id]);
            $info                 = $model->one(['id' => $id]);
            //采购装箱先删除在重新添加
            if (BaseFunction::checkJieke($this->user['role'])) {
                ContainerProductService::delContainerProduct($info['purchase_num']);
                ContainerProductService::addContainerProduct($info, $id);
            }

            $output = $re ? ['code' => 1, 'msg' => '更新成功'] : ['code' => 0, 'msg' => '更新失败,请重试'];

            return json_encode($output);
        }
    }

    /**
     *
     *采购添加界面
     */
    public function actionPurchase_add()
    {
        $model = new \app\models\Purchase();
        if (yii::$app->request->isGet) {
            $purchase_num                       = $model->generate_purchase_num();
            yii::$app->view->params['purchase'] = $purchase_num;
            yii::$app->view->params['zh_name']  = $this->user['zh_name'];
            return $this->render('purchase_add');
        }
    }

    /**
     * 老版erp采购合同生成操作
     * 增
     *
     */
    public function actionUpload_purchase()
    {
        $data  = $_POST['data'];
        $data  = json_decode($data, true);
        $model = new \app\models\Purchase();
        unset($data['zh_name']);
        if ($data['deposit_rate'] == 0) {
            $data['deposit_rate'] = 30;
        }
        $data['total_fee'] = 0;
        if ($data['ship_fee_show']) {
            $data['total_fee'] += $data['ship_fee'];
        }
        foreach ($data['product_list'] as $k => $v) {
            if (!$v['item']) {
                unset($data['product_list'][$k]);
            } else {
                $data['total_fee'] += $v['total'];
            }
        }
        $data['create_at']    = date('Y-m-d');
        $data['product_list'] = json_encode($data['product_list']);
        //添加insert
        $data['job_number'] = $this->user['job_number'];
        //生成一个采购编号
        $data['purchase_num'] = $model->generate_purchase_num();

        if ($model->insert_purchase($data)) {
            //如果是捷克采购合同产品加入排柜表
            if (BaseFunction::checkJieke($this->user['role'])) {
                $insertId = yii::$app->db->getLastInsertID();
                //加入排柜
                ContainerProductService::addContainerProduct($data, $insertId);
            }
            return json_encode(['code' => 1, 'msg' => '添加成功']);
        } else {
            return json_encode(['code' => 0, 'msg' => '添加失败，请重试2']);
        }
    }

    public function actionUpload_img()
    {
        foreach ($_FILES as $k => $v) {
            $file = $v;
            if (!$this->check_img($file['type'])) {
                echo json_encode(['code' => 0, 'msg' => '不是图片']);
                return false;
            }

            $path      = $this->get_folder();
            $suffix    = explode('.', $file['name']);
            $move_file = time() . substr(md5($file['name']), 0, 6) . '.' . $suffix[count($suffix) - 1];
            $img_url   = DIRECTORY_SEPARATOR . "upload" . DIRECTORY_SEPARATOR . date('Y-m-d')
                . DIRECTORY_SEPARATOR . $move_file;
            $re = move_uploaded_file($file['tmp_name'], $path . DIRECTORY_SEPARATOR . $move_file);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => $img_url, 'name' => $k]);
            } else {
                echo json_encode(['code' => 0, 'msg' => '添加失败，请重试']);
            }
        }
    }

    /**
     *采购合同删除
     * 删
     */
    public function actionPurchase_del()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => '请求方式不正确']);
        }
        $id = (int) yii::$app->request->post('id', 0);
        if ($id <= 0) {
            return json_encode(['code' => 0, 'msg' => '数据错误']);
        }
        $model = new Purchase();
        $info  = $model->one(['id' => $id]);
        if (!$info) {
            return json_encode(['code' => 0, 'msg' => '无此记录']);
        }
        if ($info['invoice']) {
            $invoiceModel = new Invoice_new();
            $invoiceInfo  = $invoiceModel->one(['invoice' => $info['invoice']]);
            if ($invoiceInfo['is_jiesuan'] == 3) {
                return json_encode(['code' => 0, 'msg' => '订单已结算，无法修改']);
            }
        }
        $re = $model->delete(['id' => $id]);
        ContainerProductService::delContainerProduct($info['purchase_num']);
        $output = $re ? ['code' => 1, 'msg' => '删除成功'] : ['code' => 0, 'msg' => '删除失败,请重试'];
        return json_encode($output);

    }

    // /**
    //  *采购合同更新
    //  * 改
    //  */
    // public function actionEdit_purchase()
    // {
    //     $invoice = yii::$app->request->get('id');
    //     if ($invoice) {
    //         $model = new Purchase();
    //         $info  = $model->get_purchase_by_invoice($invoice);
    //         if ($info) {
    //             $info['product_list'] = json_decode($info['product_list'], true);
    //             unset($info['id']);
    //             echo json_encode(['data' => $info, 'code' => 1]);
    //         } else {
    //             echo json_encode(['code' => 0, 'msg' => '未添加']);
    //         }
    //     }
    // }

    /**
     *询盘列表
     *
     */
    public function actionInquiry_list()
    {
        $p = yii::$app->request->get("p") ? yii::$app->request->get("p") : 1;
        $s = yii::$app->request->get("s") ? yii::$app->request->get("s") : 10;
        //
        $model = new \app\models\Inquiry();
        $size  = $model->get_inquiry_size_by_status(1);
        if ($size) {
            $page = floor($size['num'] / $s) + 1;
        } else {
            $page = 1;
        }
        $list                           = $model->get_inquiry_list_by_status($p, $s, 1);
        yii::$app->view->params['list'] = $list;
        $base_url                       = Url::to(['sell/inquiry_list']);
        yii::$app->view->params['page'] = ['page' => $page, 'curr' => $p, 'base_url' => $base_url];
        return $this->render('inquiry_list');
    }

    /**
     *  认领询盘
     */
    public function actionInquiry_update_job_number()
    {
        $id = yii::$app->request->post('id');
        //判断当前询盘id是否被认领
        if (is_numeric($id)) {
            $model = new \app\models\Inquiry();
            $info  = $model->get_inquiry_by_id($id);
            if ($info['service_name'] > 0) {
                echo json_encode(['code' => 0, 'msg' => '该询盘已被认领']);
                return false;
            }
            //更新未认领询盘
            $job_number = $this->user['job_number'];
            $re         = yii::$app->db->createCommand()
                ->update(yii::$app->db->tablePrefix . "inquiry", ['service_name' => $job_number, 'status' => 2], ['id' => $id])
                ->execute();
            if ($re) {
                $output = ['code' => 1, 'msg' => '认领成功'];
            } else {
                $output = ['code' => 0, 'msg' => '认领失败,请重试'];
            }
            echo json_encode($output);
        }
    }

    /**
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function actionDownload_pi()
    {

        $id = yii::$app->request->get('id');
        if (!is_numeric($id)) {
            return;
        }
        $model = new Pi();
        $info  = $model->get_pi_by_id($id);
        if (!$info) {
            return;
        }
        $staff_model = new Staff();
        $staff_list  = $staff_model->get_all_saleman();
        foreach ($staff_list as $v) {
            if ($v['job_number'] == $info['job_number']) {
                $info['sale_rep'] = $v['en_name'];
                $info['email']    = $v['email'];
            }
        }
        $excel         = $this->get_excel(ROOT_PATH . '/statics/excel/pi.xlsx', 'xlsx');
        $customer_info = json_decode($info['customer_info'], true);
        $excel->getActiveSheet()->setCellValue('B12', $customer_info['buyer']);
        $excel->getActiveSheet()->setCellValue('B13', $customer_info['address']);
        $excel->getActiveSheet()->setCellValue('B14', $customer_info['email']);
        $excel->getActiveSheet()->setCellValue('B15', $customer_info['tel']);
        $excel->getActiveSheet()->setCellValue('F12', $info['pi_id']);
        $excel->getActiveSheet()->setCellValue('F13', $info['date']);
        $excel->getActiveSheet()->setCellValue('F14', $info['sale_rep']);
        $excel->getActiveSheet()->setCellValue('F15', $info['email']);
        //产品录入
        $product_list = json_decode($info['product_list'], true);
        $count        = count($product_list);

        //
        if ($count > 1) {
            $excel->getActiveSheet()->insertNewRowBefore(18, $count - 1);
        }
        $total       = 0;
        $product_key = 0;
        foreach ($product_list as $k => $v) {
            $current_row = 17 + $product_key;

            $excel->getActiveSheet()->setCellValue('A' . $current_row, ($product_key + 1));
            $product_key++;
            $excel->getActiveSheet()->setCellValue('B' . $current_row, $v['item']);
            $excel->getActiveSheet()->setCellValue('D' . $current_row, $v['description']);
            $excel->getActiveSheet()
                ->getStyle('D' . $current_row)
                ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
            $excel->getActiveSheet()->setCellValue('E' . $current_row, $v['price']);
            $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');
            $excel->getActiveSheet()->setCellValue('F' . $current_row, $v['pcs']);

            $excel->getActiveSheet()->setCellValue('G' . $current_row, $v['extra_fee']);
            $excel->getActiveSheet()->getStyle('G' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $excel->getActiveSheet()->setCellValue('H' . $current_row, $v['subtotal']);
            $excel->getActiveSheet()->getStyle('H' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $total += $v['subtotal'];
            //设置图片
            if (isset($v['img_src'])) {
                $row_height = 20;
                foreach ($v['img_src'] as $k2 => $v2) {
                    $draw_excel = $this->get_excel_draw();

                    $path     = ROOT_PATH . $v2;
                    $img_info = getimagesize($path);
                    $draw_excel->setPath($path);
                    $draw_excel->setResizeProportional(false);
                    $draw_excel->setOffsetX(20);
                    $draw_excel->setOffsetY($row_height);
                    $draw_excel->setWidth(200);
                    $draw_excel->setHeight(200);
                    $draw_excel->setCoordinates('C' . $current_row);
                    $draw_excel->setWorksheet($excel->getActiveSheet());
                    $row_height += 220;
                }
                $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight($row_height - 60 * count($v['img_src']));
            } else {
                $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(80);
            }
        }
        //插入服务费
        $service = json_decode($info['service'], true);
        if ($service['show'] == "true") {
            $current_row++;
            $excel->getActiveSheet()->insertNewRowBefore($current_row, 1);
            $excel->getActiveSheet()->setCellValue('B' . $current_row, 'Service Fee');
            $excel->getActiveSheet()->setCellValue('D' . $current_row, $service['description']);
            $excel->getActiveSheet()
                ->getStyle('D' . $current_row)
                ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
            $excel->getActiveSheet()->setCellValue('E' . $current_row, $service['fee']);
            $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $excel->getActiveSheet()->setCellValue('H' . $current_row, $service['fee']);
            $excel->getActiveSheet()->getStyle('H' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $total += $service['fee'];
            $count++;
            $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(80);
        }
        //运费统计
        $ship = json_decode($info['ship'], true);

        if ($ship['show'] == "true") {
            $current_row++;
            $excel->getActiveSheet()->insertNewRowBefore($current_row, 1);
            $excel->getActiveSheet()->setCellValue('B' . $current_row, 'Shipping Fee');
            $excel->getActiveSheet()->setCellValue('D' . $current_row, $ship['description']);
            $excel->getActiveSheet()
                ->getStyle('D' . $current_row)
                ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
            $excel->getActiveSheet()->setCellValue('E' . $current_row, $ship['fee']);
            $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $excel->getActiveSheet()->setCellValue('H' . $current_row, $ship['fee']);
            $excel->getActiveSheet()->getStyle('H' . $current_row)
                ->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $total += $ship['fee'];
            $count++;
            $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(80);
        }

        //税费统计

        $service = json_decode($info['duty'], true);
        if ($service['show'] == "true") {
            $current_row++;
            $excel->getActiveSheet()->insertNewRowBefore($current_row, 1);
            $excel->getActiveSheet()->setCellValue('B' . $current_row, 'Duty Fee');
            $excel->getActiveSheet()->setCellValue('D' . $current_row, $service['description']);
            $excel->getActiveSheet()
                ->getStyle('D' . $current_row)
                ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
            $excel->getActiveSheet()->setCellValue('E' . $current_row, $service['fee']);
            $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $excel->getActiveSheet()->setCellValue('H' . $current_row, $service['fee']);
            $excel->getActiveSheet()->getStyle('H' . $current_row)
                ->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $total += $service['fee'];
            $count++;
            $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(80);
        }

        //total统计
        //判断是否开启total统计
        //移除统计数据
        $excel->getActiveSheet()->setCellValue('H' . (17 + $count), "");
        $excel->getActiveSheet()->setCellValue('G' . (17 + $count), "");

        $excel->getActiveSheet()->setCellValue('G' . (17 + $count), 'Amount:');
        $excel->getActiveSheet()->setCellValue('H' . (17 + $count), $total);
        $excel->getActiveSheet()->getStyle('H' . (17 + $count))
            ->getNumberFormat()->setFormatCode('$#,##0.00_-');

        $fill = 'A16:H' . $current_row;
        $excel->getActiveSheet()->getStyle($fill)->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

        //注解信息添加
        $para        = json_decode($info['para'], true);
        $current_row = $current_row + 4;
        foreach ($para as $k => $v) {
            $excel->getActiveSheet()->setCellValue('A' . $current_row, $v['p']);
            $current_row++;
        }

        //收款账号添加
        $pay_show = json_decode($info['pay_show'], true);
        //paypay账号移除
        if (!in_array(3, $pay_show)) {
            $excel->getActiveSheet()->removeRow(($current_row + 13), 2);
        }

        //西联
        if (!in_array(2, $pay_show)) {
            $excel->getActiveSheet()->removeRow(($current_row + 7), 5);
        }

        //TT
        if (!in_array(1, $pay_show)) {
            $excel->getActiveSheet()->removeRow(($current_row + 1), 7);
        }

        //输出
        $name = $info['pi_id'] . date('ym H:i', $info['create_at']);

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        $objWriter->save('php://output');

    }

    /**
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function actionDownload_invoice()
    {
        $id = yii::$app->request->get('id');
        if (!is_numeric($id)) {
            return;
        }
        $model = new Invoice();
        $info  = $model->get_invoice_by_id($id);
        if (!$info) {
            return;
        }
        $staff_model = new Staff();
        $staff_list  = $staff_model->get_all_saleman();
        foreach ($staff_list as $v) {
            if ($v['job_number'] == $info['job_number']) {
                $info['email']    = $v['email'];
                $info['sale_rep'] = $v['en_name'];
                break;
            }
        }
        $excel         = $this->get_excel(ROOT_PATH . '/statics/excel/invoice.xlsx', 'xlsx');
        $customer_info = json_decode($info['customer_info'], true);
        $excel->getActiveSheet()->setCellValue('B12', $customer_info['buyer']);
        $excel->getActiveSheet()->setCellValue('B13', $customer_info['address']);
        $excel->getActiveSheet()->setCellValue('B14', $customer_info['email']);
        $excel->getActiveSheet()->setCellValue('B15', $customer_info['tel']);
        $excel->getActiveSheet()->setCellValue('F12', $info['invoice_id']);
        $excel->getActiveSheet()->setCellValue('F13', $info['date']);
        $excel->getActiveSheet()->setCellValue('F14', $info['sale_rep']);
        $excel->getActiveSheet()->setCellValue('F15', $info['email']);
        //产品录入
        $product_list    = json_decode($info['product_list'], true);
        $size            = 0;
        $productList     = [];
        $discountService = [];
        foreach ($product_list as $v) {
            if (!empty($v['type']) && $v['type'] != 3) {
                $size++;
                $productList[] = $v;
            } else {
                $discountService[] = $v;
            }
        }
        $count = $size;

        //
        if ($count > 1) {
            $excel->getActiveSheet()->insertNewRowBefore(18, $count - 1);
        }
        $total        = 0;
        $product_key  = 0;
        $totalProduct = 0;
        $current_row  = 0;
        foreach ($product_list as $k => $v) {
            $current_row = 17 + $product_key;
            $totalProduct += $v['subtotal'];
            $product_key++;
            $excel->getActiveSheet()->setCellValue('A' . $current_row, $product_key);
            $excel->getActiveSheet()->setCellValue('B' . $current_row, $v['item']);
            $excel->getActiveSheet()->setCellValue('D' . $current_row, $v['description']);
            $excel->getActiveSheet()
                ->getStyle('D' . $current_row)
                ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
            $excel->getActiveSheet()->setCellValue('E' . $current_row, $v['price']);
            $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');
            $excel->getActiveSheet()->setCellValue('F' . $current_row, $v['pcs']);

            $excel->getActiveSheet()->setCellValue('G' . $current_row, $v['extra_fee']);
            $excel->getActiveSheet()->getStyle('G' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $excel->getActiveSheet()->setCellValue('H' . $current_row, $v['subtotal']);
            $excel->getActiveSheet()->getStyle('H' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(40);

            $total += $v['subtotal'];
            //设置图片
            if (!empty($v['img_src'])) {
                $row_height = 20;
                foreach ($v['img_src'] as $k2 => $v2) {
                    $draw_excel = $this->get_excel_draw();

                    $path = ROOT_PATH . $v2;
                    $draw_excel->setPath($path);
                    $draw_excel->setResizeProportional(false);
                    $draw_excel->setOffsetX(20);
                    $draw_excel->setOffsetY($row_height);
                    $draw_excel->setWidth(200);
                    $draw_excel->setHeight(200);
                    $draw_excel->setCoordinates('C' . $current_row);
                    $draw_excel->setWorksheet($excel->getActiveSheet());
                    $row_height += 220;
                }
                $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight($row_height - 60 * count($v['img_src']));
            }
        }
        //插入服务费
        $service = json_decode($info['service'], true);
        if ($service['show'] == "true") {
            $current_row++;
            $excel->getActiveSheet()->insertNewRowBefore($current_row, 1);
            $excel->getActiveSheet()->setCellValue('B' . $current_row, 'Service Fee');
            if (!empty($service['description'])) {
                $excel->getActiveSheet()->setCellValue('D' . $current_row, $service['description']);
            } else {
                $str = "The value of all products in this order is $" . $totalProduct . '.';
                if ($totalProduct <= 1000) {
                    $str .= " Service fee is $100";
                } else {
                    $str .= " Service fee rate is %s.";
                    $re  = $this->service_pay($totalProduct);
                    $str = sprintf($str, $re[1]);
                }
                $excel->getActiveSheet()->setCellValue('D' . $current_row, $str);

            }

            $excel->getActiveSheet()->setCellValue('E' . $current_row, $service['fee']);
            $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $excel->getActiveSheet()->setCellValue('H' . $current_row, $service['fee']);
            $excel->getActiveSheet()->getStyle('H' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $total += $service['fee'];
            $count++;
            $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(40);
            $excel->getActiveSheet()
                ->getStyle('D' . $current_row)
                ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
        }

        //运费统计
        $ship = json_decode($info['ship'], true);

        if ($ship['show'] == "true") {
            $current_row++;
            $excel->getActiveSheet()->insertNewRowBefore($current_row, 1);
            $excel->getActiveSheet()->setCellValue('B' . $current_row, 'Shipping Fee');
            $excel->getActiveSheet()->setCellValue('D' . $current_row, $ship['description']);
            $excel->getActiveSheet()->setCellValue('E' . $current_row, $ship['fee']);
            $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $excel->getActiveSheet()->setCellValue('H' . $current_row, $ship['fee']);
            $excel->getActiveSheet()->getStyle('H' . $current_row)
                ->getNumberFormat()->setFormatCode('$#,##0.00_-');
            $total += $ship['fee'];
            $count++;
            $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(40);
            $excel->getActiveSheet()
                ->getStyle('D' . $current_row)
                ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
        }

        //税费统计
        $service = json_decode($info['duty'], true);
        if ($service['show'] == "true") {
            $current_row++;
            $excel->getActiveSheet()->insertNewRowBefore($current_row, 1);
            $excel->getActiveSheet()->setCellValue('B' . $current_row, 'Duty Fee');
            $excel->getActiveSheet()->setCellValue('D' . $current_row, $service['description']);
            $excel->getActiveSheet()->setCellValue('E' . $current_row, $service['fee']);
            $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

            $excel->getActiveSheet()->setCellValue('H' . $current_row, $service['fee']);
            $excel->getActiveSheet()->getStyle('H' . $current_row)
                ->getNumberFormat()->setFormatCode('$#,##0.00_-');
            $total += $service['fee'];
            $count++;
            $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(40);
            $excel->getActiveSheet()
                ->getStyle('D' . $current_row)
                ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
        }
        //减免服务费添加
        $discount = 0;
        if (!empty($discountService)) {
            foreach ($discountService as $v) {
                $discount += $v['subtotal'];
                $tmp = (float) $v['subtotal'];
                $current_row++;
                $item = $v['item'] ? $v['item'] : 'Service Fee Deduction';
                $excel->getActiveSheet()->setCellValue('B' . $current_row, $item);
                $tmp = $tmp > 0 ? '-$' . abs($tmp) : '$' . abs($tmp);
                $excel->getActiveSheet()->setCellValue('E' . $current_row, $tmp);
                $excel->getActiveSheet()->setCellValue('H' . $current_row, $tmp);
                $excel->getActiveSheet()
                    ->getStyle('E' . $current_row)
                    ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER]]);

                $excel->getActiveSheet()
                    ->getStyle('H' . $current_row)
                    ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER]]);
                $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(40);
            }
        }
        $fill = 'A16:H' . $current_row;
        $excel->getActiveSheet()->getStyle($fill)->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
        //total统计
        //判断是否开启total统计
        //移除统计数据
        $current_row++;
        $total -= $discount;
        $excel->getActiveSheet()->setCellValue('G' . ($current_row), 'Amount:');
        $excel->getActiveSheet()->setCellValue('H' . ($current_row), $total);
        $excel->getActiveSheet()->getStyle('H' . ($current_row))
            ->getNumberFormat()->setFormatCode('$#,##0.00_-');
        $excel->getActiveSheet()
            ->getStyle('G' . $current_row)
            ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);

        //已付添加
        if ($info['invoice_id']) {
            $model      = new Income();
            $incomeList = $model->get_income_by_invoice($info['invoice_id']);
            $tmp        = 0;
            foreach ($incomeList as $v) {
                $a = $v['total_fee'] + $v['fee'] + $v['in_come'];
                $tmp += $a;
            }
            $tmp = round($tmp, 2);
        } else {
            $tmp = 0;
        }

        $current_row++;
        $excel->getActiveSheet()->setCellValue('G' . $current_row, 'Paid:');
        $excel->getActiveSheet()->setCellValue('H' . $current_row, $tmp);
        $excel->getActiveSheet()->getStyle('H' . ($current_row))
            ->getNumberFormat()->setFormatCode('$#,##0.00_-');
        $excel->getActiveSheet()
            ->getStyle('G' . $current_row)
            ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
        $excel->getActiveSheet()
            ->getStyle('H' . $current_row)
            ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER]]); //描述左对齐

        //未付信息添加
        $current_row++;
        $unpay = $total - $tmp;
        $excel->getActiveSheet()->setCellValue('G' . $current_row, 'Unpaid:');
        $excel->getActiveSheet()->setCellValue('H' . $current_row, $unpay);
        $excel->getActiveSheet()->getStyle('H' . ($current_row))
            ->getNumberFormat()->setFormatCode('$#,##0.00_-');
        $excel->getActiveSheet()
            ->getStyle('G' . $current_row)
            ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
        $excel->getActiveSheet()
            ->getStyle('H' . $current_row)
            ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER]]); //描述左对齐

        //注解信息添加
        $para = json_decode($info['para'], true);
        $current_row += 3;
        foreach ($para as $k => $v) {
            $excel->getActiveSheet()->setCellValue('A' . $current_row, $v['p']);
            $current_row++;
        }

        //收款账号添加
        $pay_show = json_decode($info['pay_show'], true);
        if (is_array($pay_show)) {
            //paypay账号移除
            if (!in_array(3, $pay_show)) {
                $excel->getActiveSheet()->removeRow(($current_row + 13), 2);
            }

            //西联
            if (!in_array(2, $pay_show)) {
                $excel->getActiveSheet()->removeRow(($current_row + 7), 5);
            }

            //TT
            if (!in_array(1, $pay_show)) {
                $excel->getActiveSheet()->removeRow(($current_row + 1), 7);
            }
        }

        //输出
        $name = $info['invoice_id'] . date('ym H:i', $info['create_at']);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        $objWriter->save('php://output');

    }

    /**
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function actionDownload_purchase()
    {
        $id = yii::$app->request->get('id');
        if ($id) {
            $model = new \app\models\Purchase();
            if ($info = $model->get_purchase_by_id($id)) {
                $excel = $this->get_excel(ROOT_PATH . '/statics/excel/purchase.xls', 'xls');
                $excel->getActiveSheet()->setCellValue('B4', $info['supplier_name']);
                $excel->getActiveSheet()->setCellValue('B5', $info['supplier_address']);
                $excel->getActiveSheet()->setCellValue('B6', $info['supplier_tel']);
                $excel->getActiveSheet()->setCellValue('B7', $info['qianding_address']);
                $excel->getActiveSheet()->setCellValue('E4', $info['purchase_num']);
                $excel->getActiveSheet()->setCellValue('E5', $info['qianding_date']);
                $excel->getActiveSheet()->setCellValue('E6', $info['zh_name']);
                $product_list = json_decode($info['product_list'], true);
                $count        = count($product_list);
                if ($count > 1) {
                    $excel->getActiveSheet()->insertNewRowBefore(11, $count - 1);
                }
                $sum         = 0;
                $product_key = 0;
                //excel添加产品
                foreach ($product_list as $k => $v) {
                    $column = 10 + $product_key;
                    $product_key++;
                    $excel->getActiveSheet()->setCellValue('A' . $column, $v['item']);
                    $excel->getActiveSheet()->getStyle('A' . $column)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $excel->getActiveSheet()->setCellValue('C' . $column, $v['item_detail']);
                    $excel->getActiveSheet()->getStyle('C' . $column)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $excel->getActiveSheet()->setCellValue('D' . $column, $v['num']);
                    $excel->getActiveSheet()->setCellValue('E' . $column, round($v['price'], 2));
                    $excel->getActiveSheet()->setCellValue('F' . $column, round($v['total'], 2));
                    //添加图片
                    if (isset($v['img_src']) && (!empty($v['img_src']))) {
                        foreach ($v['img_src'] as $v2) {
                            $draw_excel = $this->get_excel_draw();
                            $path       = ROOT_PATH . $v2;
                            $img_info   = getimagesize($path);
                            $draw_excel->setPath($path);
                            $draw_excel->setResizeProportional(false);
                            $draw_excel->setOffsetX(0);
                            $draw_excel->setOffsetY(20);
                            $draw_excel->setWidth(100);
                            $draw_excel->setHeight(100);
                            $draw_excel->setCoordinates('B' . $column);
                            $draw_excel->setWorksheet($excel->getActiveSheet());
                        }
                        $excel->getActiveSheet()->getRowDimension($column)->setRowHeight(100);
                    }
                    $sum += $v['total'];
                }
                //添加运费
                $current_row = $column;
                if ($info['ship_fee_show']) {
                    $sum += $info['ship_fee'];
                    $excel->getActiveSheet()->insertNewRowBefore(($current_row + 1), 1);
                    $current_row++;
                    $excel->getActiveSheet()->setCellValue('A' . $current_row, '运费');
                    $excel->getActiveSheet()->setCellValue('F' . $current_row, $info['ship_fee']);
                    $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(20);
                }
                //统计数据
                $excel->getActiveSheet()->setCellValue('F' . ($current_row + 1), $sum); //合计
                $excel->getActiveSheet()->setCellValue('F' . ($current_row + 2), $info['deposit']); //定金
                $excel->getActiveSheet()->setCellValue('F' . ($current_row + 3), $sum - $info['deposit']); //尾款

                //交货日期
                $excel->getActiveSheet()->setCellValue('D' . ($current_row + 5), $info['delivery_date']);
                //对方账户
                //结算方式
                // $account_num = str_split(trim($info['account_num']), 4);
                $str = "    户名：" . $info['account_name'] . "    收款账号："
                    . $info['account_num'] . "    开户行：" . $info['account_address'];
                $excel->getActiveSheet()->setCellValue('A' . ($current_row + 10), $str);

                //验收异议日期
                $excel->getActiveSheet()->getStyle('A' . ($current_row + 13))
                    ->getFont()->setSize(10);
                $excel->getActiveSheet()->setCellValue('A' . ($current_row + 13), $info['dissent_day']);
                $remark = "九、违约责任：\n    " . $info['remark'];
                $excel->getActiveSheet()->setCellValue('A' . ($current_row + 16), $remark);
                //业务员添加
                $model      = new Staff();
                $staff_list = $model->get_all_saleman();
                foreach ($staff_list as $k => $v) {
                    if ($v['job_number'] == $info['job_number']) {
                        $excel->getActiveSheet()->setCellValue('B' . ($current_row + 21), $v['name']);
                        break;
                    }
                }

                //公司印章添加
                $draw_excel = $this->get_excel_draw();
                $path       = ROOT_PATH . '/statics/img/seal.png';
                $img_info   = getimagesize($path);
                $draw_excel->setPath($path);
                $draw_excel->setResizeProportional(false);
                $draw_excel->setOffsetX(20);
                $draw_excel->setWidth(200);
                $draw_excel->setHeight(200);
                $draw_excel->setCoordinates('B' . ($current_row + 17));
                $draw_excel->setWorksheet($excel->getActiveSheet());

                $name = $info['purchase_num'] . date('Y-m-d');
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="' . $name . '.xls"');
                header('Cache-Control: max-age=0');
                $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
                $objWriter->save('php://output');
            }
        }
    }

    /**
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function actionDownload_quote()
    {
        $id = yii::$app->request->get('id');
        if (!is_numeric($id)) {
            return;
        }
        $model      = new \app\models\Quote();
        $info       = $model->get_quote_by_id($id);
        $staffModel = new Staff();
        $staffList  = $staffModel->get_all_saleman();
        foreach ($staffList as $key => $value) {
            if ($value['job_number'] == $info['job_number']) {
                $info['sale_rep'] = $value['en_name'];
            }
        }
        if ($info) {
            $excel         = $this->get_excel(ROOT_PATH . '/statics/excel/quote.xlsx', 'xlsx');
            $customer_info = json_decode($info['customer_info'], true);
            $excel->getActiveSheet()->setCellValue('B12', $customer_info['buyer']);
            $excel->getActiveSheet()->setCellValue('B13', $customer_info['address']);
            $excel->getActiveSheet()->setCellValue('B14', $customer_info['email']);
            $excel->getActiveSheet()->setCellValue('B15', $customer_info['tel']);
            $excel->getActiveSheet()->setCellValue('F12', $info['quote_id']);
            $excel->getActiveSheet()->setCellValue('F13', $info['date']);
            $excel->getActiveSheet()->setCellValue('F14', $info['sale_rep']);
            $excel->getActiveSheet()->setCellValue('F15', $info['email']);
            //产品录入
            $product_list = json_decode($info['product_list'], true);
            $count        = count($product_list);

            if ($info['extra_fee_show'] == '1') {
                $info['extra_fee_show'] = 'true';
            } elseif ($info['extra_fee_show'] == '0') {
                $info['extra_fee_show'] = 'false';
            }
            if ($info['subtotal_show'] == '1') {
                $info['subtotal_show'] = 'true';
            } elseif ($info['subtotal_show'] == '0') {
                $info['subtotal_show'] = 'false';
            }
            //判断是否开启extra subtotal列
            $excel->getActiveSheet()->setCellValue('H16', "");
            if ($info['extra_fee_show'] == 'false') {
                $excel->getActiveSheet()->setCellValue('G16', "");
                if ($info['subtotal_show'] == 'true') {
                    $excel->getActiveSheet()->setCellValue('G16', "Subtotal\n(USD)");
                }
            }

            if ($info['extra_fee_show'] == 'true') {
                if ($info['subtotal_show'] == 'true') {
                    $excel->getActiveSheet()->setCellValue("H16", "Subtotal\n(USD)");
                }
            }

            if ($info['subtotal_show'] == 'false') {
                $excel->getActiveSheet()->setCellValue('H16', "");
            }

            //
            if ($info['extra_fee_show'] == 'true') {
                $arr_print['G'] = "Extra\nCost";
                if ($info['subtotal_show'] == 'true') {
                    $arr_print['H'] = "Subtotal\n(USD)";
                } else {
                    $arr_print['H'] = '';
                }
            } else {
                if ($info['subtotal_show'] == 'true') {
                    $arr_print['G'] = "Subtotal\n(USD)";
                    $arr_print['H'] = "";
                } else {
                    $arr_print['G'] = '';
                    $arr_print['H'] = '';
                }
            }

            //
            if ($count > 1) {
                $excel->getActiveSheet()->insertNewRowBefore(18, $count - 1);
            }
            $total       = 0;
            $product_key = 0;
            foreach ($product_list as $k => $v) {
                $current_row = 17 + $product_key;

                $excel->getActiveSheet()->setCellValue('A' . $current_row, ($product_key + 1));
                $excel->getActiveSheet()->setCellValue('B' . $current_row, $v['item']);
                $excel->getActiveSheet()->setCellValue('D' . $current_row, $v['description']);
                $excel->getActiveSheet()
                    ->getStyle('D' . $current_row)
                    ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
                $excel->getActiveSheet()->setCellValue('E' . $current_row, $v['price']);
                $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');
                $unit = $v['unit'] ?? "pcs";
                $excel->getActiveSheet()->setCellValue('F' . $current_row, $v['pcs']);
                $product_key++;

                if ($info['extra_fee_show'] == 'true') {
                    $excel->getActiveSheet()->setCellValue('G' . $current_row, $v['extra_fee']);
                    $excel->getActiveSheet()->getStyle('G' . $current_row)->getNumberFormat()->setFormatCode('$#,##0_-');
                    if ($info['subtotal_show'] == 'true') {
                        $excel->getActiveSheet()->setCellValue('H' . $current_row, $v['subtotal']);
                        $excel->getActiveSheet()->getStyle('H' . $current_row)->getNumberFormat()->setFormatCode('$#,##0_-');
                    }
                }
                if ($info['extra_fee_show'] == 'false') {
                    if ($info['subtotal_show'] == 'true') {
                        $excel->getActiveSheet()->setCellValue('G' . $current_row, $v['subtotal']);
                        $excel->getActiveSheet()->getStyle('G' . $current_row)->getNumberFormat()->setFormatCode('$#,##0_-');
                    }
                }

                $total += $v['subtotal'];
                //设置图片
                if (isset($v['img_src'])) {
                    $row_height = 20;
                    foreach ($v['img_src'] as $k2 => $v2) {
                        $draw_excel = $this->get_excel_draw();

                        $path     = ROOT_PATH . $v2;
                        $img_info = getimagesize($path);
                        $draw_excel->setPath($path);
                        $draw_excel->setResizeProportional(false);
                        $draw_excel->setOffsetX(20);
                        $draw_excel->setOffsetY($row_height);
                        $draw_excel->setWidth(200);
                        $draw_excel->setHeight(200);
                        $draw_excel->setCoordinates('C' . $current_row);
                        $draw_excel->setWorksheet($excel->getActiveSheet());
                        $row_height += 220;
                    }
                    $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight($row_height - 60 * count($v['img_src']));
                } else {
                    $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(80);
                }
            }
            $fill = 'A16:H' . $current_row;
            $excel->getActiveSheet()->getStyle($fill)->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            //插入服务费
            $service = json_decode($info['service'], true);
            if ($service['show'] == "true") {
                $current_row++;
                $excel->getActiveSheet()->insertNewRowBefore($current_row, 1);
                $excel->getActiveSheet()->setCellValue('B' . $current_row, 'Service Fee');
                $excel->getActiveSheet()->setCellValue('D' . $current_row, $service['description']);
                $excel->getActiveSheet()->setCellValue('E' . $current_row, $service['fee']);
                $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

                $excel->getActiveSheet()->setCellValue('H' . $current_row, $service['fee']);
                $excel->getActiveSheet()->getStyle('H' . $current_row)->getNumberFormat()->setFormatCode('$#,##0_-');

                $excel->getActiveSheet()
                    ->getStyle('D' . $current_row)
                    ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
                $total += $service['fee'];
                $count++;
                $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(80);
            }
            //运费统计
            $ship = json_decode($info['ship'], true);

            if ($ship['show'] == "true") {
                $current_row++;
                $excel->getActiveSheet()->insertNewRowBefore($current_row, 1);
                $excel->getActiveSheet()->setCellValue('B' . $current_row, 'Shipping Fee');
                $excel->getActiveSheet()->setCellValue('D' . $current_row, $ship['description']);
                $excel->getActiveSheet()
                    ->getStyle('D' . $current_row)
                    ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
                $excel->getActiveSheet()->setCellValue('E' . $current_row, $ship['fee']);
                $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

                $excel->getActiveSheet()->setCellValue('H' . $current_row, $ship['fee']);
                $excel->getActiveSheet()->getStyle('H' . $current_row)
                    ->getNumberFormat()->setFormatCode('$#,##0.00_-');

                $total += $ship['fee'];
                $count++;
                $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(80);
            }

            //税费统计
            $service = json_decode($info['duty'], true);
            if ($service['show'] == "true") {
                $current_row++;
                $excel->getActiveSheet()->insertNewRowBefore($current_row, 1);
                $excel->getActiveSheet()->setCellValue('B' . $current_row, 'Duty Fee');
                $excel->getActiveSheet()->setCellValue('D' . $current_row, $service['description']);
                $excel->getActiveSheet()
                    ->getStyle('D' . $current_row)
                    ->applyFromArray(['alignment' => ['horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT]]);
                $excel->getActiveSheet()->setCellValue('E' . $current_row, $service['fee']);
                $excel->getActiveSheet()->getStyle('E' . $current_row)->getNumberFormat()->setFormatCode('$#,##0.00_-');

                $excel->getActiveSheet()->setCellValue('H' . $current_row, $service['fee']);
                $excel->getActiveSheet()->getStyle('H' . $current_row)
                    ->getNumberFormat()->setFormatCode('$#,##0.00_-');
                $total += $service['fee'];
                $count++;
                $excel->getActiveSheet()->getRowDimension($current_row)->setRowHeight(80);
            }

            //total统计
            //判断是否开启total统计
            //移除统计数据
            $excel->getActiveSheet()->setCellValue('H' . (17 + $count), "");
            $excel->getActiveSheet()->setCellValue('G' . (17 + $count), "");

            if ($info['total_amount_show'] == 'true') {
                if (!$arr_print['G']) {
                    $excel->getActiveSheet()->setCellValue('E' . (17 + $count), 'Amount:');
                    $excel->getActiveSheet()->setCellValue('F' . (17 + $count), $total);
                    $excel->getActiveSheet()->getStyle('F' . (17 + $count))
                        ->getNumberFormat()->setFormatCode('$#,##0.00_-');
                }
                if ($arr_print['G'] && (!$arr_print['H'])) {
                    $excel->getActiveSheet()->setCellValue('F' . (17 + $count), 'Amount:');
                    $excel->getActiveSheet()->setCellValue('G' . (17 + $count), $total);
                    $excel->getActiveSheet()->getStyle('G' . (17 + $count))
                        ->getNumberFormat()->setFormatCode('$#,##0.00_-');
                }
                if ($arr_print['G'] && $arr_print['H']) {
                    $excel->getActiveSheet()->setCellValue('G' . (17 + $count), 'Amount:');
                    $excel->getActiveSheet()->setCellValue('H' . (17 + $count), $total);
                    $excel->getActiveSheet()->getStyle('H' . (17 + $count))
                        ->getNumberFormat()->setFormatCode('$#,##0.00_-');
                }
            }

            //注解信息添加
            $para        = json_decode($info['para'], true);
            $current_row = $current_row + 4;
            foreach ($para as $k => $v) {
                $excel->getActiveSheet()->setCellValue('A' . $current_row, $v['p']);
                $current_row++;
            }

            $name = $info['quote_id'] . '-' . date('m-d H:i', $info['create_at']);
            //输出

            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $name . '.xls"');
            header('Cache-Control: max-age=0');
            $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
            $objWriter->save('php://output');
        }
    }

    /**
     * 我的询盘
     */
    public function actionMy_inquiry()
    {
        $job_number = $this->user['job_number'];
        $model      = new \app\models\Inquiry();
        $list       = $model->get_inquiry_list_by_job_number($job_number);
        return $this->render('my_inquiry');
    }

    /**
     * 出货列表
     */
    public function actionShipmeng_list()
    {
        $p          = yii::$app->request->get('p') ? (int) yii::$app->request->get('p') : 1;
        $s          = yii::$app->request->get('s') ? (int) yii::$app->request->get('s') : 15;
        $job_number = $this->user['job_number'];
        $model      = new \app\models\Shipment();
        $where      = [];
        //size
        if ($this->user['role'] == 1) {
            $size = $model->get_shipment_size('', $where);
            $list = $model->get_all_shipment_by_saleman('', $p, $s, $where);
        } else {
            $size = $model->get_shipment_size($job_number, $where);
            $list = $model->get_all_shipment_by_saleman($job_number, $p, $s, $where);
        }
        if ($size) {
            $page  = ($size['num'] / $s) ? (floor($size['num'] / $s) + 1) : (floor($size['num'] / $s));
            $total = $size['num'];
        } else {
            $page  = 1;
            $total = 0;
        }
        //list
        yii::$app->view->params['list'] = $list;

        //所有快递类型
        $model                                  = new \app\models\Express();
        $express_list                           = $model->get_express_type();
        yii::$app->view->params['express_list'] = $express_list;
        $url                                    = '/sell/shipmeng_list' . $this->get_base_url();
        yii::$app->view->params['page']         = ['total' => $total, 'page' => $page, 'curr' => $p, 'url' => $url];

        return $this->render('shipment_list');
    }

    public function actionShipment_add()
    {
        $model                          = new \app\models\Express();
        $list                           = $model->get_express_type();
        yii::$app->view->params['list'] = $list;
        $customer_model                 = new \app\models\Customer();
        $customer_list                  = $customer_model->get_all_customer();
        foreach ($customer_list as $k => $v) {
            $customer_list[$k]['value'] = $v['customer_name'];
        }
        yii::$app->view->params['customer_list'] = $customer_list;
        return $this->render('shipment_add');
    }

    //添加操作
    public function actionShipment_add_act()
    {
        if (yii::$app->request->isPost) {
            $data              = yii::$app->request->post('data');
            $data['saleman']   = $this->user['job_number'];
            $data['create_at'] = time();
            $re                = yii::$app->db->createCommand()
                ->insert(yii::$app->db->tablePrefix . "shipment", $data)
                ->execute();
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '添加失败，请重试']);
            }
        }
    }

    public function actionShipment_edit()
    {
        if (yii::$app->request->isGet) {
            $id                             = yii::$app->request->get('id');
            $model                          = new \app\models\Shipment();
            $info                           = $model->get_shipment_by_id($id);
            yii::$app->view->params['info'] = $info;

            //快递列表
            $model                          = new \app\models\Express();
            $list                           = $model->get_express_type();
            yii::$app->view->params['list'] = $list;

            return $this->render("shipment_edit");
        }
    }

    //运货编辑操作
    public function actionShipment_edit_act()
    {
        if (yii::$app->request->isPost) {
            $data = yii::$app->request->post('data');
            $id   = $data['id'];
            unset($data['id']);

            //update
            $re = yii::$app->db
                ->createCommand()
                ->update(yii::$app->db->tablePrefix . 'shipment', $data, ['id' => $id])
                ->execute();

            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '添加失败，请重试']);
            }
        }
    }

    //上传出货列表
    public function actionShipment_import()
    {
        if (yii::$app->request->isPost) {
            $file     = $_FILES['print'];
            $is_excel = \app\lib\BaseFunction::check_excel($file['type']);
            if ($is_excel) {
                $path      = $this->get_folder();
                $move_file = $path . '/' . substr(md5(time()), 0, 6) . $file['name'];
                move_uploaded_file($file['tmp_name'], $move_file);
                chmod($move_file, 0755);

                //读取excel
                $objPHPExcel   = $this->get_excel($move_file, explode('.', $file['name'])[1]);
                $objWorksheet  = $objPHPExcel->getActiveSheet();
                $highestRow    = $objWorksheet->getHighestRow();
                $highestColumn = $objWorksheet->getHighestColumn();

                $exceldata = [];
                for ($i = 2; $i < $highestRow; $i++) {
                    $invoice = $objPHPExcel->getActiveSheet()->getCell('B' . $i)->getValue();
                    if ($invoice) {
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('A' . $i)->getValue();
                        $exceldata[$i][] = $invoice;
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('C' . $i)->getValue();
                        $tmp             = $objPHPExcel->getActiveSheet()->getCell('D' . $i)->getValue();
                        if (is_string($tmp)) {
                            $exceldata[$i][] = $tmp;
                        } else {
                            $exceldata[$i][] = date('Y-m-d', ($tmp - 25569) * 24 * 60 * 60);
                        }

                        $real_ship_date = $objPHPExcel->getActiveSheet()->getCell('E' . $i)->getValue();
                        if (is_string($real_ship_date)) {
                            $exceldata[$i][] = $real_ship_date;
                        } else {
                            $exceldata[$i][] = date('Y-m-d', ($real_ship_date - 25569) * 24 * 60 * 60);
                        }

                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('F' . $i)->getValue();
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('G' . $i)->getValue();
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('H' . $i)->getValue();
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('I' . $i)->getValue();
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('J' . $i)->getValue();
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('K' . $i)->getValue();
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('L' . $i)->getValue();
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('M' . $i)->getValue();
                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('N' . $i)->getValue();
                        $tmp             = $objPHPExcel->getActiveSheet()->getCell('O' . $i)->getValue();
                        if (is_string($tmp)) {
                            $exceldata[$i][] = $tmp;
                        } else {
                            $exceldata[$i][] = date('Y-m-d', ($tmp - 25569) * 24 * 60 * 60);
                        }

                        $tmp = $objPHPExcel->getActiveSheet()->getCell('P' . $i)->getValue();
                        if (is_string($tmp)) {
                            $exceldata[$i][] = $tmp;
                        } else {
                            $exceldata[$i][] = date('Y-m-d', ($tmp - 25569) * 24 * 60 * 60);
                        }

                        $exceldata[$i][] = $objPHPExcel->getActiveSheet()->getCell('Q' . $i)->getValue();
                    }
                };
                $keys = [
                    'pi', 'invoice', 'status', 'predict_date', 'real_ship_date', 'customer_name', 'saleman',
                    'ship_type', 'express_id', 'address', 'product', 'weight', 'cbm', 'num',
                    'port_date', 'real_date', 'remark',
                ];
                $re = yii::$app->db->createCommand()
                    ->batchInsert(yii::$app->db->tablePrefix . 'shipment', $keys, $exceldata)
                    ->execute();
                if ($re) {
                    echo json_encode(['code' => 1, 'msg' => '添加成功']);
                } else {
                    echo json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
                }
            } else {
                echo json_encode(['msg' => '不是excel文件', 'code' => 0]);
            }
        }
    }

    //内陆费用添加
    public function actionInland()
    {
        return $this->render('inland');
    }

    /**
     *装箱列表api
     *
     */
    public function actionContainerList()
    {
        $page             = yii::$app->request->get('page', 1);
        $pageSize         = yii::$app->request->get('pageSize', 10);
        $where            = [];
        $where['date']    = yii::$app->request->get('date');
        $where['number']  = yii::$app->request->get('number');
        $where['invoice'] = yii::$app->request->get('invoice');
        $where['status']  = yii::$app->request->get('status');
        $model            = new ContainerModel();
        $list             = $model->all($where, ($page - 1) * $pageSize, $pageSize, ['date' => SORT_DESC]);
        $size             = $model->size($where);
        return json_encode(['list' => $list, 'total' => $size]);
    }

    /**
     * 货运装柜信息添加
     *
     **/
    public function actionContainerAdd()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => 'not allowed']);
        }
        $data              = yii::$app->request->post();
        $data['create_at'] = time();
        $data['staff']     = $this->user['job_number'];
        if (!$data['number']) {
            return \json_encode(['code' => 0, 'msg' => '没有装箱编号']);
        }
        $model = new ContainerModel();
        $info  = $model->one(['number' => $data['number']]);
        if ($info) {
            return json_encode(['code' => 0, 'msg' => '装箱编号已存在,请修改']);
        }
        $re     = $model->insert($data);
        $output = $re ? ['code' => 1, 'msg' => '添加成功'] : ['code' => 0, 'msg' => '添加失败,请重试'];
        return json_encode($output);
    }

    /**
     *装箱信息修改
     *
     */
    public function actionContainerUpdate()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'not allowed']);
        }
        $data = yii::$app->request->post();
        foreach ($data as $key => $value) {
            if (!in_array($key, ['value', 'column', 'id'])) {
                return \json_encode(['code' => 0, 'msg' => '参数错误']);
            }
        }

        $model = new ContainerModel();
        $re    = $model->save([$data['column'] => $data['value']], ['id' => $data['id']]);
        if ($re) {
            if ($data['column'] == 'status') {
                //装柜信息出货将产品修改成出库状态
                //先获取装箱编号
                $info = $model->one(['id' => $data['id']]);
                if ($info) {
                    if ($data['value'] == 2) {
                        $saveData = ['status' => 3];
                    } elseif ($data['value'] == 1) {
                        $saveData['status'] = 2;
                    }
                    $model = new ContainerProductModel();
                    $model->save($saveData, ['container_num' => $info['id']]);
                }

            }

        }
        $output = $re ? ['code' => 1, 'msg' => '更新成功'] : ['code' => 0, 'msg' => '更新失败'];
        return json_encode($output);
    }

    /**
     *排柜界面
     *@return string
     */
    public function actionContainerProductList()
    {
        $page                  = yii::$app->request->get('page', 1);
        $pageSize              = yii::$app->request->get('pageSize', 10);
        $status                = yii::$app->request->get('status', '');
        $number                = yii::$app->request->get('number', '');
        $number                = $number ? substr($number, 6) : '';
        $where                 = [];
        $where['purchase_num'] = yii::$app->request->get('purchase_num', '');
        $where['name']         = yii::$app->request->get('name', '');
        $where['begin_time']   = yii::$app->request->get('begin_time', '');
        $where['end_time']     = yii::$app->request->get('end_time', '');
        $container_num         = yii::$app->request->get('container_num', '');
        if ($container_num) {
            //获取装箱编号
            $containerModel = new ContainerModel();
            $record         = $containerModel->one(['number' => $container_num]);
            $container_num  = $record ? $record['id'] : false;
        }
        //1全部2未出货3出货4未排柜
        if ($status == 1) {
        } elseif ($status == 2) {
            $where['status'] = [1, 2];
        } elseif ($status == 3) {
            $where['status'] = 3;
        } elseif ($status == 4) {
            $where['container_num_empty'] = true;
        } elseif ($status == 5) {
            $where['container_num_empty'] = false;
        }
        //搜索优先级更高
        if (!empty($container_num) || !empty($number)) {
            $where['container_num'] = $container_num ? $container_num : $number;
        }

        $model = new ContainerProductModel();
        //有货柜编号
        if ((!empty($where['container_num'])) || (!empty($where['name']))) {
            $list  = $model->all($where, ($page - 1) * $pageSize, $pageSize, ['create_at' => SORT_DESC, 'id' => SORT_DESC]);
            $totalPage = (int) $model->size($where);
        } else {
            $where['split_pid'] = 0;
            $list               = $model->all($where, ($page - 1) * $pageSize, $pageSize, ['create_at' => SORT_DESC, 'id' => SORT_DESC]);
            $pidArr             = array_column($list, 'id');
            $list2              = $model->all(['split_pid' => $pidArr]);
            foreach ($list as $k => $v) {
                foreach ($list2 as $k2 => $v2) {
                    if ($v['id'] == $v2['split_pid']) {
                        $list[$k]['children'][] = $v2;
                    }
                }
            }
            foreach ($list as $key => $value) {
                if (isset($value['children'])) {
                    $list[$key]['childsum'] = array_sum(array_column($value['children'], 'num'));
                } else {
                    $list[$key]['childsum'] = 0;
                }
            }
            if ($status == 4) {
                foreach ($list as $k => $v) {
                    if (isset($v['children'])) {
                        foreach ($v['children'] as $k2 => $v2) {
                            if ($v2['container_num'] != '') {
                                unset($list[$k]['children'][$k2]);
                            }
                        }
                    }
                }
            }
            $totalPage = (int) $model->size($where);
        }
        //获取采购编号计算已付未付信息
        $purchaseNumArr = array_column($list, 'purchase_num');
        $bankModel      = new Bank_bill();
        $payList        = $bankModel->getPurchaseNumPay($purchaseNumArr, 'purchase_num,in_money,out_money');
        //获取采购编号订单总金额
        $model      = new Purchase();
        $needPay    = $model->all(['purchase_num' => $purchaseNumArr]);
        $needPayArr = [];
        foreach ($needPay as $key => $v) {
            $needPayArr[$v['purchase_num']] = $v['total_fee'];
        }
        $tmp = [];
        foreach ($payList as $v) {
            $m = $v['out_money'] - $v['in_money'];
            if (isset($tmp[$v['purchase_num']])) {
                $tmp[$v['purchase_num']] += $m;
            } else {
                $tmp[$v['purchase_num']] = $m;
            }
        }

        foreach ($list as $k => $v) {
            if (!isset($tmp[$v['purchase_num']])) {
                $tmp[$v['purchase_num']] = 0;
            }
            //订单已付金额
            $moneyAll            = $tmp[$v['purchase_num']];
            $notPay              = $needPayArr[$v['purchase_num']] - $moneyAll;
            $rate                = ($v['num'] * $v['price']) / $needPayArr[$v['purchase_num']];
            $list[$k]['havePay'] = round($moneyAll * $rate, 2);
            $list[$k]['notPay']  = round($notPay * $rate, 2);
        }

        //捷克部门总已付总未付金额计算
        $jiekeGroup     = StaffService::jiekeGroup();
        $jiekeJobnumber = array_column($jiekeGroup, 'job_number');
        $totalPay       = $model->sumTotalPay(['job_number' => $jiekeJobnumber]); //总需要支出
        $sql            = "SELECT sum(out_money-in_money) as money FROM `jingsourcing_bank_bill` WHERE purchase_num IN
        (SELECT purchase_num FROM `jingsourcing_purchase` WHERE job_number IN (" . implode($jiekeJobnumber, ',') . ") AND `create_at`>='2018-01-01') AND date>='2018-01-01'";
        $re = yii::$app->db->createCommand($sql)->queryOne();
        //已付定金已付尾款计算
        //未收款记录 未收款的采购编号

        //先获取所有采购合同付款金额
        $sql               = "SELECT sum(out_money-in_money) as money,purchase_num FROM jingsourcing_bank_bill WHERE service_name IN (" . implode($jiekeJobnumber, ',') . ") AND purchase_num!='' GROUP BY purchase_num";
        $tmpList           = yii::$app->db->createCommand($sql)->queryAll();
        $purchaseMoneyList = [];
        foreach ($tmpList as $key => $value) {
            $purchaseMoneyList[$value['purchase_num']] = $value['money'];
        }
        // echo json_encode($purchaseMoneyList);exit;
        //获取所有捷克采购编号总额
        $sql               = "SELECT purchase_num,total_fee FROM jingsourcing_purchase WHERE job_number IN (" . implode($jiekeJobnumber, ',') . ") AND purchase_num !=''";
        $purchaseList      = yii::$app->db->createCommand($sql)->queryAll();
        $purchaseTotalList = [];
        foreach ($purchaseList as $key => $v) {
            $purchaseTotalList[$v['purchase_num']] = $v['total_fee'];
        }
        // echo json_encode($purchaseTotalList);exit;
        //获取所有未付款柜子
        $sql     = "SELECT * FROM jingsourcing_container WHERE status!=3";
        $guilist = array_column(yii::$app->db->createCommand($sql)->queryAll(), 'id');
        $sql     = "SELECT * FROM jingsourcing_container_product WHERE flag=1";
        //获取已收款采购合同

        $allList = yii::$app->db->createCommand($sql)->queryAll();
        $ding    = 0; //已付定金
        $quan    = 0; //已付尾款
        $notPay  = 0;
        foreach ($allList as $key => $v) {
            if ((!$v['container_num']) || ($v['container_num'] && in_array($v['container_num'], $guilist))) {
                //整个订单总金额
                $total = isset($purchaseTotalList[$v['purchase_num']]) ? $purchaseTotalList[$v['purchase_num']] : 0;
                $pay   = isset($purchaseMoneyList[$v['purchase_num']]) ? $purchaseMoneyList[$v['purchase_num']] : 0;

                if ($total > 0) {
                    //当前记录总金额
                    $currentTotal = $v['num'] * $v['price'];
                    if ($currentTotal > 0) {
                        $currentPay = $currentTotal / $total * $pay;
                        if ($currentPay / $currentTotal > 0.85) {
                            $quan += $currentPay;
                        } else {
                            $ding += $currentPay;
                            // echo $ding;
                        }
                        $notPay += $currentTotal - $currentPay;
                    }

                }

            }
        }
        // $sql = "SELECT a.purchase_num FROM jingsourcing_container_product a
        //         LEFT JOIN jingsourcing_container b ON a.container_num=b.id
        //         WHERE b.status=3";
        // $havePayList = array_column(yii::$app->db->createCommand($sql)->queryAll(), 'purchase_num');
        // echo json_encode($havePayList);exit;
        // $ding   = 0; //已付定金
        // $quan   = 0; //已付尾款
        // $notPay = 0;
        // foreach ($purchaseList as $k => $v) {
        //     if (!in_array($v['purchase_num'], $havePayList)) {
        //         foreach ($tmpList as $k2 => $v2) {
        //             if ($v['purchase_num'] == $v2['purchase_num']) {
        //                 if ($v2['money'] / $v['total_fee'] > 0.85) {
        //                     $quan += $v2['money'];
        //                 } else {
        //                     $ding += $v2['money'];
        //                     $notPay += $v['total_fee'] - $v2['money'];
        //                 }
        //             }
        //         }
        //     }
        // }
        return \json_encode(['tongji' => ['ding' => $ding, 'quan' => $quan, 'notPay' => $notPay], 'list' => $list, 'total' => $totalPage, 'totalPay' => $totalPay, 'havePay' => $re['money']]);
    }

    /**
     *排柜界面产品删除
     *
     *@return string
     */
    public function actionContainerProductDel()
    {
        if (!Yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'methods not allowed']);
        }
        $id = yii::$app->request->post('id', '');
        if (!is_numeric($id) || $id <= 0) {
            return json_encode(['code' => 0, 'msg' => '数据错误']);
        }

        $model  = new ContainerProductModel();
        $re     = $model->delete(['id' => $id]);
        $result = $re ? ['code' => 1, 'msg' => "删除成功"] : ['code' => 0, 'msg' => '删除失败，请重试'];
        return json_encode($result);
    }

    /**
     * 排柜拆分
     *@return string
     */
    public function actionContainerProductSplit()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'method not allowed']);
        }

        $data  = yii::$app->request->post();
        $rules = [[['num', 'id'], 'required']];
        try {
            $validator = yii\base\DynamicModel::validateData($data, $rules);
            if ($msg = $validator->hasErrors()) {
                return \json_encode(['code' => 0, 'msg' => $msg]);
            }
            //数据拆分
            $model  = new ContainerProductModel();
            $record = $model->one(['id' => $data['id']]);
            //已出货无法拆分
            if ($record['status'] == 3) {
                return json_encode(['code' => 0, 'msg' => '已经出货，无法拆分']);
            }
            if ($record['split_pid'] != 0) {
                return \json_encode(['code' => 0, 'msg' => '当前记录不能拆分']);
            }
            //原始數據需要貨櫃編號為空
            $re                   = $model->save(['flag' => 2, 'container_num' => ''], ['id' => $data['id']]);
            $tmp                  = $record;
            $tmp['num']           = $data['num'];
            $tmp['container_num'] = $data['container_num'];
            $tmp['split_pid']     = $record['id'];
            $tmp['flag']          = 1;
            unset($tmp['id']);
            $re     = $model->insert($tmp);
            $output = $re ? ['code' => 1, 'msg' => '拆分成功'] : ['code' => 0, 'msg' => '拆分失败,请重试'];
            return \json_encode($output);
        } catch (\Exception $e) {
            yii::error($e->getMessage());
            return \json_encode(['code' => 0, 'msg' => '系统错误']);
        }
    }

    /**
     *排柜界面修改
     *@return string
     */
    public function actionContainerProductUpdate()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'method not allowed']);
        }

        $data  = yii::$app->request->post();
        $rules = [[['id', 'column', 'value'], 'required']];
        try {
            $validator = yii\base\DynamicModel::validateData($data, $rules);
            if ($msg = $validator->hasErrors()) {
                return \json_encode(['code' => 0, 'msg' => $msg]);
            }
            $model  = new ContainerProductModel();
            $re     = $model->save([$data['column'] => $data['value']], ['id' => $data['id']]);
            $output = $re ? ['code' => 1, 'msg' => '更新成功'] : ['code' => 0, 'msg' => '更新失败'];
            return \json_encode($output);
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            return json_encode(['code' => 0, 'msg' => $msg]);
        }
    }

    /**
     *装箱合并
     *@return string
     */
    public function actionContainerProductCombine()
    {
        if (!yii::$app->request->isPost) {
            return \json_encode(['code' => 0, 'msg' => 'method not allowed']);
        }
        $id = yii::$app->request->post('id', '');
        if (!is_numeric($id) || $id < 0) {
            return json_encode(['code' => 0, 'msg' => '数据错误']);
        }
        //校验id是否为拆分数据
        $model = new ContainerProductModel();
        $info  = $model->one(['id' => $id]);
        if (!$info) {
            return \json_encode(['code' => 0, 'msg' => '当前记录不存在']);
        }
        if ($info['split_pid'] > 0) {
            return \json_encode(['code' => 0, 'msg' => '当前记录是拆分项，无法合并']);
        }
        //当前项已经出货或者子项出货无法合并
        if ($info['status'] == 3) {
            return json_encode(['code' => 0, 'msg' => '当前记录已经出货，无法合并']);
        }
        $list = $model->all(['split_id' => $id]);
        foreach ($list as $key => $value) {
            if ($value['status'] == 3) {
                return json_encode(['code' => 0, 'msg' => '当前记录已经出货，无法合并']);
            }
        }
        //刪除子项
        $trans = yii::$app->db->beginTransaction();
        try {
            $model->delete(['split_pid' => $id]);
            $model->save(['flag' => 1], ['id' => $id]);
            $trans->commit();
        } catch (\Exception $e) {
            $trans->rollBack();
            return \json_encode(['code' => 0, 'msg' => '合并失败，请重试']);
        }
        return \json_encode(['code' => 1, 'msg' => '合并成功']);

    }
}
